package com.linkage.seapeak.activity.vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.adapter.Vote.EditVoteMemberGroupAdapter;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.net.ResultCallBack;
import com.linkage.seapeak.net.VoteNetRequest;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.utils.ToastUtil;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 编辑选择表决成员 无分组
 * 返回值为 List<CrediterUser> 对应键名为 result
 *
 */
public class EditVoteMemberNoGroupActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    private static final int REQUEST_CODE_MEMBER = 0xf1;
    private static final int REQUEST_CODE_MONEY = 0xf2;
    private String projectId;
    private String voteId;

    private int voteType;
    private int voteRule;

    private AYSwipeRecyclerView mRecyclerView;
    private RelativeLayout emptyView;
    private View bottomLay;
    private EditVoteMemberGroupAdapter mDataAdapter;

    private List mData;
    private int moneyIndex = 0;

    int count = 0;

    int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pro_vote_voters_no_group, "表决人员");
        projectId = getIntent().getStringExtra("projectId");
        voteId = getIntent().getStringExtra("voteId");
        voteType = getIntent().getIntExtra("voteType", -1);
        voteRule = getIntent().getIntExtra("voteRule", -1);
        init();
        mRecyclerView.startLoadFirst();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_MEMBER && resultCode == RESULT_OK && data != null) {
//            List<CrediterUser> userList = (List<CrediterUser>) data.getSerializableExtra("userList");
////            HashMap<String, String> parms = (HashMap<String, String>) data.getSerializableExtra("parms");
////            addVoteMember(parms, userList, data.getIntExtra("selectType", -1));
            loadFirst();
            notifyDataChanged();
        } else if (requestCode == REQUEST_CODE_MONEY && resultCode == RESULT_OK && data != null) {
            CrediterUser user = (CrediterUser) mData.get(moneyIndex);
            turnMoney(user, data.getDoubleExtra("money", 0d));
        }
    }

    /**
     * 重新计算，刷新
     */
    public void notifyDataChanged() {
        setTitle(mData.size() == 0 ? "表决人员（0）" : "表决人员(" + count + ")");
        emptyView.setVisibility(mData.size() == 0 ? View.VISIBLE : View.GONE);
        bottomLay.setVisibility(mData.size() != 0 ? View.VISIBLE : View.GONE);
        mRecyclerView.onFinishRequest(false, mData.size() < count);
    }

    public void init() {
        mRecyclerView = findViewById(R.id.list);
        emptyView = findViewById(R.id.empty);
        bottomLay = findViewById(R.id.bottom_lay);

        mData = new ArrayList<>();
        mDataAdapter = new EditVoteMemberGroupAdapter(EditVoteMemberNoGroupActivity.this, mData);
        mRecyclerView.setAdapter(mDataAdapter);
        mRecyclerView.setShowEmpty(false);
        mRecyclerView.setOnRefreshLoadLister(this);
        mRecyclerView.setMode(AYSwipeRecyclerView.SwipeType.BOTH);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EditVoteMemberNoGroupActivity.this, VoteMemberMultiSelectActivity.class);
                intent.putExtra("projectId", projectId);
                intent.putExtra("voteId", voteId);
                intent.putExtra("voteType", voteType);
                intent.putExtra("grouped", "0");
                startActivityForResult(intent, REQUEST_CODE_MEMBER);
            }
        });

        mDataAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                switch (v.getId()) {
                    case R.id.voter_change:
                        moneyIndex = position;
                        Intent intent = new Intent(EditVoteMemberNoGroupActivity.this, VoteTurnMoneyActivity.class);
                        intent.putExtra("money", ((CrediterUser) mData.get(moneyIndex)).getVoteMoney());
                        startActivityForResult(intent, REQUEST_CODE_MONEY);
                        break;
                    case R.id.btnDelete:
                        CrediterUser user = (CrediterUser) mData.get(position);
                        deleteUser(user);
                        break;
                }
            }
        });

        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editComplete();
            }
        }, "完成", 0));
        findViewById(R.id.add_member).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> ids = new ArrayList<>();
                for (CrediterUser user : ((List<CrediterUser>)mData)){
                    ids.add(user.getCreditorid());
                }
                Intent intent = new Intent(EditVoteMemberNoGroupActivity.this, VoteMemberMultiSelectActivity.class);
                intent.putExtra("projectId", projectId);
                intent.putExtra("alreadySelectIds", (Serializable) ids);
                intent.putExtra("canSelectAlready", true);
                intent.putExtra("voteId", voteId);
                intent.putExtra("voteType", voteType);
                intent.putExtra("grouped", "0");
                startActivityForResult(intent, REQUEST_CODE_MEMBER);
            }
        });
        findViewById(R.id.create_ids).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress();
                VoteNetRequest.getMeetingNumber(getUserToken(), voteId, projectId, voteRule + "", new ResultCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        hideProgress();
                        showToast("生成成功", ToastUtil.TOAST_TYPE.SUCCESS);
//                        getEditVoteMember();
                        loadFirst();
                    }

                    @Override
                    public void onFailed(String msg) {
                        showToast(msg);
                        hideProgress();
                    }
                });
            }
        });
    }

    /**
     * 完成修改
     */
    private void editComplete() {

        if(count == 0)
        {
            noticeDialog = new PublicNoticeDialog(EditVoteMemberNoGroupActivity.this, new View.OnClickListener(){

                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.ll_close:
                            noticeDialog.dismiss();
                            break;
                        case R.id.btn_chancel_notice:
                            noticeDialog.dismiss();
                            if (count != 0)
                                clearVoteMember();
                            else
                                finish();
                            break;
                        case R.id.btn_save_notice:
                            noticeDialog.dismiss();
                            if (count != 0)
                                editComplete();
                            break;
                    }
                }
            }, 1,"提示",count != 0 ? "是否保存选择的表决成员？" : "还没有添加任何成员哦~",
                    count != 0 ?  "不保存" : "暂不添加",count != 0 ? "保存" : "去添加");
            noticeDialog.show();
            return;
        }


        showProgress();
        VoteNetRequest.editComplete(getUserToken(), voteId, projectId, voteRule + "", new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                Intent intent = new Intent();
//                intent.putExtra("result", (Serializable) mData);
                intent.putExtra("count", count);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 获取列表
     */
    private void getEditVoteMember() {
        Network.getAPIService()
                .getOrAddVoteMemberTable(getUserToken(), voteId, "", projectId, page + "", "20",
                        voteRule == -1 ? "" : voteRule + "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            notifyDataChanged();
                        } else {
                            JsonObject jsonObject = json.getAsJsonObject("data").getAsJsonObject("data");
                            JsonArray groupArray = jsonObject.getAsJsonArray("list");
                            count = jsonObject.get("totalCount").getAsInt();

                            List<CrediterUser> crediterUsers = new ArrayList<>();
                            if (groupArray != null) {
                                for (int i = 0;i < groupArray.size();i++) {
                                    CrediterUser user = new Gson().fromJson(groupArray.get(i).toString(), CrediterUser.class);
                                    crediterUsers.add(user);
                                }
                            }
                            if (page == 1)
                                mData.clear();
                            page++;
                            mData.addAll(crediterUsers);
                            notifyDataChanged();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    /**
     * 设置金额
     * @param user
     * @param money
     */
    private void turnMoney(final CrediterUser user, final double money) {
        showProgress();
        VoteNetRequest.turnVoteMoney(getUserToken(), user.getId(), money, voteId, "",  new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                user.setVoteMoney(money);
                user.setDeclareAsVote(false);
                notifyDataChanged();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 删除人员
     * @param user
     */
    private void deleteUser(final CrediterUser user) {
        showProgress();
        VoteNetRequest.deleteVoteMember(getUserToken(), voteId, user.getId(), new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                mData.remove(user);
                loadFirst();
                notifyDataChanged();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 添加人员
     * @param userList
     */
    private void addVoteMember(HashMap<String, String> parms, final List<CrediterUser> userList, int type) {
        loadFirst();
        showProgress();
//        VoteNetRequest.addVoteMember(getUserToken(), parms, type, voteId, projectId,  userList, new ResultCallBack<String>() {
//            @Override
//            public void onSuccess(String result) {
//                hideProgress();
//                loadFirst();
//            }
//
//            @Override
//            public void onFailed(String msg) {
//                hideProgress();
//                showToast(msg);
//            }
//        });
    }

    @Override
    public void loadFirst() {
        page = 1;
        getEditVoteMember();
    }

    @Override
    public void loadNext() {
        getEditVoteMember();
    }

    /**
     * 清空人员
     */
    private void clearVoteMember() {
        showProgress();
        VoteNetRequest.clearVoteMember(getUserToken(), voteId, new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                count = 0;
                finish();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
//                finish();
                showToast(msg);
            }
        });
    }

    private PublicNoticeDialog noticeDialog;

    @Override
    public void backEvent() {
        noticeDialog = new PublicNoticeDialog(EditVoteMemberNoGroupActivity.this, new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_close:
                        noticeDialog.dismiss();
                        break;
                    case R.id.btn_chancel_notice:
                        noticeDialog.dismiss();
                        if (count != 0)
                            clearVoteMember();
                        else
                            finish();
                        break;
                    case R.id.btn_save_notice:
                        noticeDialog.dismiss();
                        if (count != 0)
                            editComplete();
                        break;
                }
            }
        }, 1,"提示",count != 0 ? "是否保存选择的表决成员？" : "还没有添加任何成员哦~",
                count != 0 ?  "不保存" : "暂不添加",count != 0 ? "保存" : "去添加");
        noticeDialog.show();
    }
}
